<?php 
namespace App\Services\User;

use App\Facades\Infra\User\WeChatManage;
use App\Facades\Infra\User\GiRecordManage;
use App\Exceptions\CreateDataException;

class GiRecordService{

	public function record($data){

		$userId = $this->getUserId();

		$conditions = [
			'wechat_user_id' => $userId
		];

		if(count(GiRecordManage::getRecordToDay($conditions)) > 0){
			throw new CreateDataException('今日已经存在数据');
		}

		$data['wechat_user_id'] = $userId;

		GiRecordManage::createRecord($data);

	}

	public function todayHasCreate(){
		$userId = $this->getUserId();

		$conditions = [
			'wechat_user_id' => $userId
		];

		$giRecord = GiRecordManage::getRecordToDay($conditions);

		if(count($giRecord) > 0){
			return $giRecord[0];
		}

		return null;
	}

	public function getRecordById($data){
		$id=$data['id'];

		return GiRecordManage::getRecordById($id);
	}

	public function getRecordList(){

		$conditions['wechat_user_id'] = $this->getUserId();

		return GiRecordManage::getRecordList($conditions);
	}

	public function updateTodayRecord($data){

		$conditions = [
			'id' => $data['id'],
			'wechat_user_id' => $this->getUserId()
		];

		if(count(GiRecordManage::getRecordToDayAndId($conditions)) < 1){
			throw new CreateDataException('只能修改当天数据');
		}

		GiRecordManage::updateRecord($data['id'],$data);
	}

	private function getUserId(){
		$openid = session('wechat.oauth_user')->getId();

		$conditions['openid'] = $openid;

		$wechatUser = WeChatManage::getUserInfo($conditions);

		return $wechatUser->id;
	}
}